package com.xyz.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xyz.entity.mapper.*;
import com.xyz.entity.pojo.*;
import com.xyz.service.CommonService;
import com.xyz.service.RoleService;
import com.xyz.util.dto.DataResult;
import com.xyz.util.dto.GridData;
import com.xyz.util.dto.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Autowired
    private SystemEmployeeMapper systemEmployeeMapper;

    @Autowired
    private SystemRoleMapper systemRoleMapper;

    @Autowired
    private SystemRoleDirectoryMapper systemRoleDirectoryMapper;

    @Override
    public DataResult selectUserInfo(LoginInfo li) throws Exception {
        SystemEmployee se = systemEmployeeMapper.selectByPrimaryKey(li.getLoginEmployeeId());
        Map<String, Object> map = new HashMap<>();
        map.put("id", se.getId());
        map.put("username", li.getLoginUsername());
        map.put("roleName", li.getLoginRoleName());
        map.put("employeeName", se.getEmployeeName());
        map.put("phoneNumber", se.getPhoneNumber());
        map.put("positionName", commonService.getDictMap("TYPE_EMPLOYEE_POSITION").getOrDefault(se.getPosition(), ""));
        map.put("headFileCode", se.getHeadFileCode());
        map.put("isMessage", se.getIsMessage());
        map.put("loginTime", DateUtil.formatDateTime(li.getLoginTime()));
        map.put("lastLoginTime", DateUtil.formatDateTime(li.getLastLoginTime()));
        map.put("directory", commonService.getDirectory(0, li.getLoginRoleId()));
        return DataResult.build9100(map);
    }

    @Override
    public DataResult selectRole(LoginInfo li, int pageNum, int pageSize, String roleName) throws Exception {
        SystemRoleExample srExample = new SystemRoleExample();
        SystemRoleExample.Criteria srCriteria = srExample.createCriteria();
        if (StrUtil.isNotBlank(roleName)) {
            srCriteria.andRoleNameLike("%" + roleName + "%");
        }
        srCriteria.andIsDeleteEqualTo(0);
        srExample.setOrderByClause("create_time");
        Page<SystemRole> page = PageHelper.startPage(pageNum, pageSize);
        List<SystemRole> srList = systemRoleMapper.selectByExample(srExample);
        List<Map<String, Object>> list = new ArrayList<>();
        for (SystemRole sr : srList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", sr.getId());
            map.put("roleName", sr.getRoleName());
            list.add(map);
        }
        return DataResult.build9100(new GridData(page.getTotal(), list));
    }

    @Override
    public DataResult insertRole(LoginInfo li, String roleName) throws Exception {
        SystemRoleExample srExample = new SystemRoleExample();
        srExample.createCriteria().andIsDeleteEqualTo(0).andRoleNameEqualTo(roleName);
        if (systemRoleMapper.countByExample(srExample) > 0) {
            return DataResult.build9250("角色名称重复");
        }
        SystemRole newSr = new SystemRole();
        newSr.setRoleName(roleName);
        newSr.setIsDelete(0);
        newSr.setCreateTime(new Date());
        systemRoleMapper.insert(newSr);
        return DataResult.build9100();
    }

    @Override
    public DataResult updateRole(LoginInfo li, long roleId, String roleName) throws Exception {
        if (roleId == 1L) {
            return DataResult.build9250("超级管理员无法修改或删除");
        }
        SystemRoleExample srExample = new SystemRoleExample();
        srExample.createCriteria().andIsDeleteEqualTo(0).andIdNotEqualTo(roleId).andRoleNameEqualTo(roleName);
        if (systemRoleMapper.countByExample(srExample) > 0) {
            return DataResult.build9250("角色名称重复");
        }
        SystemRole newSr = new SystemRole();
        newSr.setId(roleId);
        newSr.setRoleName(roleName);
        systemRoleMapper.updateByPrimaryKeySelective(newSr);
        return DataResult.build9100();
    }

    @Override
    public DataResult deleteRole(LoginInfo li, long roleId) throws Exception {
        if (roleId == 1L) {
            return DataResult.build9250("超级管理员无法修改或删除");
        }

        SystemUser newSu = new SystemUser();
        newSu.setRoleId(0L);
        SystemUserExample suExample = new SystemUserExample();
        suExample.createCriteria().andRoleIdEqualTo(roleId);
        systemUserMapper.updateByExampleSelective(newSu, suExample);

        SystemRole newSr = new SystemRole();
        newSr.setId(roleId);
        newSr.setIsDelete(1);
        systemRoleMapper.updateByPrimaryKeySelective(newSr);
        return DataResult.build9100();
    }

    @Override
    public DataResult selectDirectoryByRoleId(LoginInfo li, long roleId) throws Exception {
        return DataResult.build9100(commonService.getDirectory(1, roleId));
    }

    @Override
    public DataResult updateDirectoryByRoleId(LoginInfo li, long roleId, String directoryIds) throws Exception {
        if (roleId == 1L) {
            return DataResult.build9250("超级管理员无法修改或删除");
        }
        List<Long> directoryIdList = new ArrayList<>();
        for (String directoryId : directoryIds.split(",")) {
            directoryIdList.add(Long.parseLong(directoryId));
        }

        SystemRoleDirectoryExample srdExample = new SystemRoleDirectoryExample();
        srdExample.createCriteria().andRoleIdEqualTo(roleId);
        systemRoleDirectoryMapper.deleteByExample(srdExample);

        SystemRoleDirectory newSrd = new SystemRoleDirectory();
        for (long directoryId : directoryIdList) {
            newSrd.setRoleId(roleId);
            newSrd.setDirectoryId(directoryId);
            systemRoleDirectoryMapper.insert(newSrd);
        }

        return DataResult.build9100();
    }

    @Override
    public DataResult selectUserByRoleId(LoginInfo li, int pageNum, int pageSize, long roleId) throws Exception {
        SystemRoleExample srExample = new SystemRoleExample();
        srExample.createCriteria().andIsDeleteEqualTo(0);
        List<SystemRole> srList = systemRoleMapper.selectByExample(srExample);
        Map<Long, String> srMap = new HashMap<>();
        for (SystemRole sr : srList) {
            srMap.put(sr.getId(), sr.getRoleName());
        }

        SystemEmployeeExample seExample = new SystemEmployeeExample();
        seExample.createCriteria().andIsDeleteEqualTo(0);
        List<SystemEmployee> seList1 = systemEmployeeMapper.selectByExample(seExample);
        Map<Long, String> seMap = new HashMap<>();
        for (SystemEmployee se : seList1) {
            seMap.put(se.getId(), se.getEmployeeName());
        }

        SystemUserExample suExample = new SystemUserExample();
        SystemUserExample.Criteria suCriteria = suExample.createCriteria();
        suCriteria.andRoleIdEqualTo(roleId);
        suCriteria.andIsDeleteEqualTo(0);
        suExample.setOrderByClause("create_time");
        Page<SystemUser> page = PageHelper.startPage(pageNum, pageSize);
        List<SystemUser> suList = systemUserMapper.selectByExample(suExample);
        List<Map<String, Object>> list = new ArrayList<>();
        for (SystemUser su : suList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", su.getId());
            map.put("username", su.getUsername());
            map.put("employeeName", seMap.getOrDefault(su.getEmployeeId(), ""));
            map.put("roleName", srMap.getOrDefault(su.getRoleId(), ""));
            map.put("lastLoginTime", DateUtil.formatDateTime(su.getLastLoginTime()));
            map.put("createTime", DateUtil.formatDateTime(su.getCreateTime()));
            list.add(map);
        }
        return DataResult.build9100(new GridData(page.getTotal(), list));
    }

    @Override
    public DataResult insertUserByRoleId(LoginInfo li, long roleId, String userIds) throws Exception {
        List<Long> userIdList = new ArrayList<>();
        for (String userIdStr : userIds.split(",")) {
            userIdList.add(Long.parseLong(userIdStr));
        }
        if (roleId == 1L || userIdList.contains(1L)) {
            return DataResult.build9250("超级管理员无法修改或删除");
        }
        SystemUser newSu = new SystemUser();
        newSu.setRoleId(roleId);
        for (Long userId : userIdList) {
            newSu.setId(userId);
            systemUserMapper.updateByPrimaryKeySelective(newSu);
        }
        return DataResult.build9100();
    }

    @Override
    public DataResult deleteUserByRoleId(LoginInfo li, long userId) throws Exception {
        if (userId == 1L) {
            return DataResult.build9250("超级管理员无法修改或删除");
        }
        SystemUser newSu = new SystemUser();
        newSu.setId(userId);
        newSu.setRoleId(0L);
        systemUserMapper.updateByPrimaryKeySelective(newSu);
        return DataResult.build9100();
    }

}
